<?php
namespace App\Actions;

use App\Actions\BaseAction;
use App\Models\AdminUser;
use App\Models\Department;
use App\Models\DyBaseInfo;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DyHookAction extends BaseAction
{
    public $model;
    public $admin_user;

    public function __construct(Model $model = null, AdminUser $adminUser = null)
    {
        $this->admin_user = $adminUser;
    }

    public function updateMainRow($relation_row, $relation_table)
    {
        # 这是这个身份证号码的第一个上传信息为主要记录
        DB::table($relation_table)->where('sfz', $relation_row->sfz)->update(['is_main' => 0]);
        $first_row = DB::table($relation_table)->where('sfz', $relation_row->sfz)->orderBy('created_at', 'asc')->orderBy('id', 'asc')->first();
        if ($first_row) {
            DB::table($relation_table)->where('id', $first_row->id)->update(['is_main' => 1]);
        }
    }

    public function afterCreatedOrEdit($relation_row, $relation_table, $is_create = false, $params = [])
    {
        # 这是这个身份证号码的第一个上传信息为主要记录
        $this->updateMainRow($relation_row, $relation_table);
    }


    public function afterDelete($relation_row, $relation_table, $params = [])
    {
        $this->updateMainRow($relation_row, $relation_table);
    }

    /**
     * 处理党员导入的数据
     */
    public function dealDbData($all_datas, $table)
    {
        $dwdm = $this->admin_user->dwdm;

        foreach($all_datas as $_data) {
            # 判断数据是否重复
            $_data['dwmc'] = $this->admin_user->dwmc;
            $_data['dwdm'] = $this->admin_user->dwdm;
            $_data['updated_by_gid'] = $this->admin_user->gid;
            $_data['updated_at'] = date("Y-m-d H:i:s");
            $_data['is_main'] = 0;
            try {
                if ($table == 'dy_base_infos') {
                    $jrsj = isset($_data['jrsj']) ? $_data['jrsj'] : '';
                    $zrzssj = isset($_data['zrzssj']) ? $_data['zrzssj'] : '';
                    $return = DyBaseInfo::getRadioInfo($_data['sfz'], $jrsj, $zrzssj);
                    $_data['is_underage'] = $return['is_underage'];
                    $_data['is_less_year'] = $return['is_less_year'];

                    # 职称等级
                    $_data['zcjb'] = isset($_data['zc']) && $_data['zc'] ? DyBaseInfo::getZcjb($_data['zc']) : '';
                }
            } catch (\Throwable $th) {
                Log::info("{$table}导入问题：" . $th->getMessage());
            }
            $is_insert = true;
            if ($_data['sfz']) {
                # 该单位是否已经存在一个相同身份证号码的人
                $current_dw_model = DB::table($table)->where('sfz', $_data['sfz'])->where('dwdm', $this->admin_user->dwdm)->first();
                if ($current_dw_model) {
                    DB::table($table)->where('sfz', $_data['sfz'])->where('dwdm', $this->admin_user->dwdm)->update($_data);
                    $id = $current_dw_model->id;
                    $is_insert = false;
                }
            }
            if ($is_insert) {
                $_data['created_by_gid'] = $this->admin_user->gid;
                $_data['created_at'] = date("Y-m-d H:i:s");
                $id = DB::table($table)->insertGetId($_data);
            }

            $relation_row = DB::table($table)->where('id', $id)->first();
            $this->updateMainRow($relation_row, $table);
        }
    }

    /**
     * 处理修改的数据
     */
    public function dealEditData($inputs, Model $model = null)
    {
        if (isset($inputs['_inline_edit_']) && $inputs['_inline_edit_']) {
            # 行内编辑
            return $this->dealDyInlineData($inputs, $model);
        }

        $inputs = collect($inputs)->except(['_token', '_method', '_previous_'])->all();

        $table = $model->getTable();
        $modelClass = get_class($model);
        $is_edit = $model->id ? true : false;
        $is_super_admin = $this->admin_user->isSuperManger();
        if (!$is_edit) {
            # 新增
            if (isset($inputs['dwdm']) && $is_super_admin) {
                $dwdm = $inputs['dwdm'];
            } else {
                $dwdm = $this->admin_user->dwdm;
            }
            if ($modelClass::query()->where('sfz', $inputs['sfz'])->where('dwdm', $dwdm)->exists()) {
                $this->error('身份证号已经存在');
            }
        } else {
            # 修改
            if ($modelClass::query()->where('sfz', $inputs['sfz'])->where('dwdm', $model->dwdm)->where('id', '<>', $model->id)->exists()) {
                $this->error('身份证号已经存在');
            }
            $dwdm = $model->dwdm;
        }
        
        $filter_data = collect($inputs)->only($modelClass::$edit_fields)->filter()->all();
        if (in_array($table, ['dy_xfzdys', 'dy_qrs', 'dy_qcs', 'dy_fzdxs', 'dy_jjfzs'])) {
            $errors = $modelClass::validators($filter_data, $dwdm, $is_super_admin);
        } else {
            $errors = $modelClass::validators($filter_data);
        }
        
        if ($errors) {
            $inputs['is_error'] = 1;
            $inputs['errors'] = json_encode($errors);
            $this->error(implode("<br/>", $errors));
        } else {
            $inputs['is_error'] = 0;
            $inputs['errors'] = json_encode([]);
        }
        # 判断是否成年，预备期是否满一年
        if ($table == 'dy_base_infos') {
            $jrsj = isset($inputs['jrsj']) ? $inputs['jrsj'] : '';
            $zrzssj = isset($inputs['zrzssj']) ? $inputs['zrzssj'] : '';
            $return = DyBaseInfo::getRadioInfo($inputs['sfz'], $jrsj, $zrzssj);
            $inputs['is_underage'] = $return['is_underage'];
            $inputs['is_less_year'] = $return['is_less_year'];

            # 职称等级
            $inputs['zcjb'] = isset($inputs['zc']) && $inputs['zc'] ? DyBaseInfo::getZcjb($inputs['zc']) : '';
        }

        $inputs['updated_by_gid'] = $this->admin_user->gid;
        $inputs['updated_at'] = date("Y-m-d H:i:s");
        if (!$is_edit) {
            $inputs['dwdm'] = $dwdm;
            if (isset($inputs['dwdm']) && $is_super_admin) {
                $department = Department::query()->where('dwdm', $dwdm)->first();
                $inputs['dwmc'] = $department ? $department->dwmc : '';
            } else {
                $inputs['dwmc'] = $this->admin_user->dwmc;
            }
            $inputs['created_by_gid'] = $this->admin_user->gid;
            $inputs['created_at'] = date("Y-m-d H:i:s");
            $relation_row = $modelClass::create($inputs);
            $this->updateMainRow($relation_row, $table);
        } else {
            $orign_sfz = $model->sfz; # 原来的身份证号码
            $model->update($inputs);

            # 如果是组织部人员修改，需要把相同身份证人员的信息同时改掉
            if ($table == 'dy_base_infos' && $this->admin_user->isSuperManger()) {
                $same_models = DyBaseInfo::query()->where('sfz', $inputs['sfz'])->where('id', '<>', $model->id)->get();
                foreach($same_models as $same_model) {
                    $same_model->update($inputs);
                }
            }
    
            # 如果修改了身份证
            if ($orign_sfz != $inputs['sfz']) {
                $this->updateMainRow($model, $table);

                $origin_model = $modelClass::query()->where('sfz', $orign_sfz)->first();
                if ($origin_model) {
                    $this->updateMainRow($origin_model, $table);
                }
            }
        }

        
    }

    /**
     * 党员信息行内编辑
     */
    public function dealDyInlineData($inputs, Model $model)
    {
        $table = $model->getTable();
        $modelClass = get_class($model);
        $filter_data = collect($inputs)->only($modelClass::$edit_fields)->all();
        $field = '';
        foreach(collect($filter_data)->keys() as $key) {
            $field = $key ? $key : '';
        }
        if (!$field) {
            $this->error('此处无法修改，请使用编辑按钮进行数据修改');
        }
        if ($table == 'dy_xfzdys' || in_array($table, ['dy_xfzdys', 'dy_qrs', 'dy_qcs', 'dy_fzdxs', 'dy_jjfzs'])) {
            $errors = $modelClass::validatorsFoInline($field, collect($filter_data)->filter()->all(), $model->toArray(), $this->admin_user->isSuperManger());
        } else {
            $errors = $modelClass::validatorsFoInline($field, collect($filter_data)->filter()->all(), $model->toArray());
        }
        
        if ($errors) {
            $this->error(implode("<br/>", $errors));
        }

        if ($field == 'sfz' && $modelClass::query()->where('sfz', $inputs['sfz'])->where('dwdm', $model->dwdm)->where('id', '<>', $model->id)->exists()) {
            $this->error('身份证号已经存在');
        }

        $update_data = $filter_data;
        $update_data['is_error'] = 0;
        $update_data['errors'] = json_encode([]);
        $inputs['updated_by_gid'] = $this->admin_user->gid;
        $inputs['updated_at'] = date("Y-m-d H:i:s");
        if ($field == 'sfz') {
            $orign_sfz = $model->sfz; # 原来的身份证号码
        }
        if ($table == 'dy_base_infos' && $field == 'zc') {
            # 如果修改了职称，需要对应修改职称等级
            $update_data['zcjb'] = isset($inputs['zc']) && $inputs['zc'] ? DyBaseInfo::getZcjb($inputs['zc']) : '';
        }
        $model->update($update_data);

        $new_update = [];
        if (in_array($field, ['zrzssj', 'jrsj', 'sfz']) && $table == 'dy_base_infos') {
            $jrsj = $model->jrsj ? $model->jrsj : '';
            $zrzssj = $model->zrzssj ? $model->zrzssj : '';
            $return = DyBaseInfo::getRadioInfo($model->sfz, $jrsj, $zrzssj);
            $new_update['is_underage'] = $return['is_underage'];
            $new_update['is_less_year'] = $return['is_less_year'];
            DB::table($table)->where('id', $model->id)->update($new_update);
        }

        # 如果是组织部人员修改，需要把相同身份证人员的信息同时改掉
        if ($table == 'dy_base_infos' && $this->admin_user->isSuperManger()) {
            $same_update = array_merge($update_data, $new_update);
            $same_models = DyBaseInfo::query()->where('sfz', $model->sfz)->where('id', '<>', $model->id)->get();
            foreach($same_models as $same_model) {
                $same_model->update($same_update);
            }
        }
        // if ($field == 'sfz' && isset($orign_sfz) && $orign_sfz != $update_data['sfz']) {
        //     # 修改了身份证，先修改本次新身份证的信息
        //     $this->updateMainRow($model, $table);

        //     $origin_model = $modelClass::query()->where('sfz', $orign_sfz)->first();
        //     if ($origin_model) {
        //         # 修改了身份证，旧身份证信息响应修改
        //         $this->updateMainRow($origin_model, $table);
        //     }
        // }
        
    }

    /**
     * Create a form instance.
     *
     * @param  mixed  ...$params
     * @return $this
     */
    public static function make(...$params)
    {
        return new static(...$params);
    }
}
